﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LX.Web.Security;
using S4Store.Domain;
using S4Store.Service;

namespace S4Store.Controllers
{
    public class LoginController : BaseController
    {
        public ISafeCodeProvider SafeCodeProvider { get; set; }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(string username,string password,string safecode)
        {
            if(!SafeCodeProvider.ValidSafeCode(Session.SessionID,safecode))
            {
                throw new Exception("验证码错误");
            }
            using(var t=new Transtion())
            {
                t.Inject(AdministratorService);
                Administrator administrator = AdministratorService.Login(username, password);
                AdministratorService.SetTicket(administrator);

                t.Commit();
                removecookie();
                return new JsonResult
                           {
                               Data = new { success = true }
                           };
            }
        }

        private void removecookie()
        {
            HttpCookie cookieStoreId = new HttpCookie("StoreId");
            cookieStoreId.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookieStoreId);
            HttpCookie cookiemonth = new HttpCookie("Month");
            cookiemonth.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookiemonth);
            HttpCookie cookieStart = new HttpCookie("Start");
            cookieStart.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookieStart);
            HttpCookie cookieEnd = new HttpCookie("End");
            cookieEnd.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookieEnd);

        }
    }
}
